#asp.net boilerplate development services
Explore tagged Tumblr posts
Text
Master Angular 18 and ASP.NET 8.0: Your Gateway to Modern Web Development
Web development continues to evolve at an astonishing pace, with frameworks and technologies constantly being updated. If you’re keen on mastering two of the most in-demand skills, Angular 18 and ASP.NET 8.0, you’re on the right track. Together, these tools form a powerhouse duo for creating efficient, scalable, and dynamic web applications. In this article, we’ll explore why these technologies are vital, how they work together, and how you can leverage them to boost your career in web development.
What Makes Angular 18 and ASP.NET 8.0 Stand Out?
Angular 18: A Frontend Marvel
Angular 18, the latest version of Google’s popular TypeScript-based framework, comes packed with features that make frontend development smoother and more efficient. Its ability to handle complex Single Page Applications (SPAs) with ease makes it a go-to for developers. Key highlights include:
Enhanced Performance: Faster rendering and improved change detection.
Streamlined Tooling: Debugging and testing have become easier.
Modular Architecture: Encourages better organization and scalability.
ASP.NET 8.0: Backend Brilliance
ASP.NET 8.0 is a robust framework for building web APIs and dynamic server-side applications. Microsoft has added cutting-edge features in this version, such as:
Minimal APIs: Simplified development for RESTful services.
Better Integration with Blazor: Enhances full-stack development capabilities.
Improved Performance: Faster execution and resource management.
Why Combine Angular and ASP.NET?
Pairing Angular 18 with ASP.NET 8.0 creates a synergy that benefits both developers and end-users. Angular handles the frontend, providing a seamless user interface (UI), while ASP.NET manages the backend, ensuring secure data processing and storage. Together, they deliver high-performing applications that are user-friendly and robust.
Top Features of Angular 18
1. Signals for State Management
Angular 18 introduces Signals, a reactive system for managing state updates. This feature simplifies how data flows within an application.
2. Enhanced Dependency Injection (DI)
Angular’s improved DI makes it easier to manage services and reusable components, ensuring cleaner code.
3. Standalone Components
With standalone components, developers can now build and use components without having to include them in Angular modules, reducing overhead.
Top Features of ASP.NET 8.0
1. Minimal APIs for Simplified Development
Creating web APIs is now faster with minimal boilerplate code.
2. gRPC Performance Enhancements
Efficient communication between services using gRPC ensures better data handling and faster response times.
3. Cross-Platform Compatibility
Run your applications seamlessly across different operating systems.
How to Get Started with Angular 18 and ASP.NET 8.0
1. Setting Up the Development Environment
To begin, ensure you have the following installed:
Node.js and npm: For Angular development.
Visual Studio 2022: Ideal for ASP.NET projects.
.NET 8 SDK: Required for ASP.NET 8.0.
2. Building a Simple Angular Application
Start with a basic Angular project:
bash
Copy code
ng new my-angular-app
cd my-angular-app
ng serve
This command sets up a new Angular project and runs it locally.
3. Creating a Web API with ASP.NET 8.0
In Visual Studio, create a new project and select ASP.NET Core Web API. Add minimal API code like this:
csharp
Copy code
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello, World!");
app.Run();
Best Practices for Combining Angular and ASP.NET
1. Use RESTful APIs
Ensure your backend provides RESTful endpoints that your Angular frontend can consume effortlessly.
2. Leverage Dependency Injection
Both Angular and ASP.NET use DI to promote reusable and testable code.
3. Optimize for Performance
Minimize unnecessary API calls and use tools like Angular’s Ahead-of-Time (AOT) compilation to speed up your app.
Building a Real-World Project
Imagine creating an e-commerce platform with Angular 18 as the frontend and ASP.NET 8.0 as the backend. Here’s a high-level breakdown:
Frontend: Angular handles product pages, shopping carts, and user interactions.
Backend: ASP.NET manages user authentication, payment processing, and database operations.
Career Opportunities with Angular 18 and ASP.NET 8.0
1. High Demand in the Job Market
Skills in Angular and ASP.NET are highly sought after, making you a valuable asset to any company.
2. Diverse Roles
From full-stack developer to frontend specialist, mastering these tools opens up numerous career paths.
3. Freelancing and Entrepreneurship
Build your own apps or take up freelance projects, leveraging these technologies.
Learning Resources for Angular 18 and ASP.NET 8.0
1. Online Courses
Look for courses that focus on Master Angular 18 and ASP.NET 8.0 to get hands-on experience.
2. Official Documentation
Both Angular and ASP.NET have detailed guides to help you understand their features and implementation.
3. Community Support
Join forums and developer communities to share knowledge and solve issues.
Common Challenges and How to Overcome Them
1. Steep Learning Curve
Both Angular and ASP.NET have rich ecosystems, which can be overwhelming. Start small and focus on mastering core concepts first.
2. Integration Issues
Ensure your frontend and backend are well-synced by using tools like Postman for testing APIs.
3. Debugging Complex Applications
Utilize debugging tools like Chrome DevTools for Angular and Visual Studio’s debugger for ASP.NET.
Future Trends in Angular and ASP.NET Development
1. Enhanced AI Integration
Expect more AI-powered tools and libraries to integrate seamlessly with these frameworks.
2. Serverless Architectures
ASP.NET is already paving the way for serverless development.
3. Progressive Web Apps (PWAs)
Angular continues to be a preferred framework for building PWAs, ensuring better user experiences.
Conclusion
Mastering Angular 18 and ASP.NET 8.0 is a smart move for anyone looking to excel in modern web development. Together, they offer the perfect combination of power, flexibility, and efficiency, enabling you to build everything from dynamic SPAs to scalable web APIs. Whether you’re a beginner or an experienced developer, these technologies are worth your investment.
0 notes
Text
Why Choose ASP.NET for Web Application Development in 2024?
ASP.NET is still a top technology framework for web application development, with a rich ecosystem for building strong, scalable, and secure applications. The most recent improvements in 2024 have increased its capabilities, making it a top choice for businesses globally.
Top Benefits of Using ASP.NET for Web Development in 2024
Improved Performance and Scalability
The most recent ASP.NET upgrades for 2024 provide performance optimization improvements that improve application speed and reduce memory consumption. The framework's built-in caching, asynchronous programming, and support for microservices make it ideal for applications that demand scalability.
Cross-Platform Development with.NET Core.
ASP.NET Core enables developers to create applications that run on a variety of platforms, including Windows, macOS, and Linux. This flexibility enables enterprises to reach a larger audience while also ensuring that their applications are future-proof.
Security Features:
With an increase in cybersecurity threats, ASP.NET includes built-in security capabilities like as request validation, authentication, authorization, and data encryption. The 2024 improvements enhance security by integrating identity and access management technologies.
MVC Architecture
ASP.NET The MVC architecture separates application functionality and UI layers, allowing developers to write clear, maintainable code. This also improves the application's scalability because individual components can be updated or modified without affecting the entire application.
Support for cloud and microservices.
ASP.NET works well with cloud services such as Azure, allowing developers to create scalable, cloud-native apps. Businesses can use microservices architecture to construct complex applications that are simple to deploy and manage.
What's New in ASP.NET 2024: Key Features and Updates
Improved Blazor IntegrationBlazor, the front-end framework for building interactive web UIs using C#, has seen enhancements in 2024. Developers can now build even more dynamic, real-time applications with enhanced WebAssembly capabilities.
Minimal APIs The latest ASP.NET updates introduce minimal APIs that allow developers to quickly build lightweight, fast web services with reduced boilerplate code. This feature is perfect for startups and businesses needing rapid API development.
Containerization and Kubernetes Integration ASP.NET 2024 comes with better support for containerization, allowing seamless integration with Kubernetes for deploying, managing, and scaling applications. This update enables businesses to adopt modern DevOps practices with ease.
gRPC SupportASP.NET now fully supports gRPC, a high-performance, open-source framework for remote procedure calls. This is particularly useful for building real-time applications that require low-latency communication between services.
Why Hire a Dedicated ASP.NET Developer?
Expertise in ASP.NET EcosystemA dedicated ASP.NET developer brings in-depth knowledge of the framework, ensuring the development process is smooth and efficient. They are skilled in leveraging the latest features and updates to build high-performing web applications.
Cost-Effective DevelopmentHiring a dedicated ASP.NET developer or team ensures cost-effective development. Outsourcing or remote hiring allows you to access top talent without the overhead costs associated with full-time, in-house staff.
Customization and ScalabilityA dedicated ASP.NET developer can tailor your application to meet your unique business needs and ensure scalability as your business grows. They can also provide ongoing support and maintenance.
Faster Time to MarketExperienced ASP.NET developers can accelerate the development process, allowing you to launch your application faster and gain a competitive edge.
Techcronus – Your Trusted ASP.NET Development Partner
At Techcronus, we specialize in building high-performance web applications using ASP.NET. Our team of certified ASP.NET developers delivers customized solutions to meet your business goals. Whether you're looking to build a new application or optimize an existing one, Techcronus can help you at every step.
Contact us today! Contact No: +91 79-40399641 / +1 (415) 234-7510 Email: [email protected]
For more information, visit our official website to explore our services and case studies.
#ASPNetDevelopment#WebDevelopment#ASPNetCore#DotNetDevelopment#WebAppDevelopment#DotNetCore#ASPNetMVC#CustomWebSolutions#TechSolutions#BusinessApplications#ScalableWebApps#SecureWebApplications#WebDevelopmentServices#DigitalTransformation#BusinessGrowth#InnovativeTech#EnterpriseWebApps#OpenSourceDevelopment#CrossPlatformDevelopment#RapidAppDevelopment#EasyCodeManagement#HighSecuritySolutions#ScalableSolutions
0 notes
Text
Powering the Future: Top Backend Frameworks for Developers in 2024
The backend, the unseen engine that drives web applications, is undergoing constant evolution. Backend frameworks provide developers with essential tools and structures to build robust, scalable, and secure web applications. In 2024, several established frameworks continue to dominate the landscape, while new contenders emerge with exciting features. This guide explores the top backend frameworks developers should consider for their 2024 projects.
Established Powerhouses:
Django (Python):
A mature and versatile framework known for its "batteries included" philosophy, providing a wide range of built-in features for rapid development.
Ideal for complex web applications, e-commerce platforms, and content management systems (CMS) due to its robust security features and scalability.
Python's popularity and extensive libraries further enhance Django's appeal.
Spring Boot (Java):
A popular choice for enterprise-level applications, known for its modular design and focus on developer productivity.
Simplifies development by auto-configuration and dependency injection, reducing boilerplate code.
Spring Boot's vast ecosystem of libraries and tools caters to diverse project needs.
Laravel (PHP):
A feature-rich framework offering a clean and expressive syntax for PHP development.
Laravel excels at building APIs and web applications with robust security features and a thriving community.
Its focus on rapid development and MVC (Model-View-Controller) architecture makes it popular for building complex web projects.
ASP.NET Core (C#):
Microsoft's open-source framework for building modern web applications.
Offers cross-platform compatibility, allowing development for Windows, Linux, and macOS.
Strong integration with other Microsoft technologies like Azure cloud platform makes it attractive for enterprise development.
Rising Stars:
FastAPI (Python):
Gaining rapid traction for its focus on high performance and developer experience.
Leverages Python's type hints for static type checking, enhancing code reliability.
Ideal for building modern APIs requiring speed, efficiency, and a clean development workflow.
NestJS (JavaScript/TypeScript):
A server-side framework for building scalable Node.js applications with a strong focus on architecture and testability.
Employs TypeScript for static typing and leverages design patterns like dependency injection for better code organization.
Ideal for large-scale, complex web applications requiring a structured and maintainable codebase.
Choosing the Right Framework:
Selecting the best backend framework depends on your project's specific needs and your team's skillset. Here are some key factors to consider:
Project Requirements: Evaluate the complexity, scale, and performance needs of your project.
Programming Language Expertise: Choose a framework built on a language your team is comfortable with.
Development Speed and Maintainability: Consider the framework's features and structure to optimize development efficiency and code maintainability.
Security: Prioritize frameworks with a strong focus on security best practices.
Community and Support: A large and active community allows for easier access to support and learning resources.
Beyond the Framework: The Importance of Skills
While frameworks provide valuable tools, developer skillset remains paramount. A strong understanding of programming languages, object-oriented programming (OOP) principles, database management, and security best practices is essential for building robust backend applications.
The Future of Backend Frameworks
The future of backend frameworks lies in:
Microservices Architecture: Breaking down applications into smaller, independent services for increased scalability and maintainability.
Cloud-Native Development: Optimizing frameworks for deployment and management on cloud platforms like AWS, Azure, and Google Cloud Platform (GCP).
Artificial Intelligence (AI) Integration: Leveraging AI for tasks like code generation, testing, and performance optimization.
Conclusion:
Backend frameworks empower developers to build the backbone of the digital world. In 2024, the established powerhouses continue to deliver, while rising stars like FastAPI and NestJS offer exciting possibilities for modern web application development. By understanding your project needs, considering these factors, and fostering strong developer skills, you can choose the framework that helps you build successful and future-proof applications.
0 notes
Text
0 notes
Link
Concept Infoway is a Microsoft Certified Company and we have some of the best ASP.NET Boilerplate developers in the USA. We have a team of highly professional ASP.NET Boilerplate developers who are well-versed with every aspect of ASP.NET Boilerplate development.
#asp.net boilerplate development company#asp.net boilerplate development services#asp.net core#asp.net boilerplate development#asp.net boilerplate#.net boilerplate development services
0 notes
Text
Exploring a minimal Web API with ASP.NET Core 6
I write about minimal Web APIs in 2016 and my goal has always been for "dotnet server.cs" to allow for a single file simple Web API. Fast forward to 2021 and there's some great work happening again in the minimal API space!
Let's do a 'dotnet new web' with the current .NET 6 preview. I'm on .NET 6 preview 7. As mentioned in the blog:
We updated .NET SDK templates to use the latest C# language features and patterns. We hadn’t revisited the templates in terms of new language features in a while. It was time to do that and we’ll ensure that the templates use new and modern features going forward.
The following language features are used in the new templates:
Top-level statements
async Main
Global using directives (via SDK driven defaults)
File-scoped namespaces
Target-typed new expressions
Nullable reference types
This is pretty cool. Perhaps initially a bit of a shock, but this a major version and a lot of work is being done to make C# and .NET more welcoming. All your favorite things are still there and will still work but we want to explore what can be done in this new space.
Richard puts the reasoning very well:
The templates are a much lower risk pivot point, where we’re able to set what the new “good default model” is for new code without nearly as much downstream consequence. By enabling these features via project templates, we’re getting the best of both worlds: new code starts with these features enabled but existing code isn’t impacted when you upgrade.
This means you'll see new things when you make something totally new from scratch but your existing stuff will mostly work just fine. I haven't had any trouble with my sites.
Let's look at a super basic hello world that returns text/plain:
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); if (app.Environment.IsDevelopment()){ app.UseDeveloperExceptionPage(); } app.MapGet("/", () => "Hello World!"); app.Run();
Slick. Note that I made line 3 (which is optional) just be one line to be terse. Not needed, just trying on these new shoes.
If we make this do more and support MVC, it's just a little larger. I could add in app.MapRazorPages() if I wanted instead of MapControllerRoute, which is what I use on my podcast site.
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
Back to the original Web API one. I can add Open API support by adding a reference to Swashbuckle.AspNetCore and then adding just a few lines:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.MapGet("/", () => "Hello World!"); app.UseSwaggerUI(); app.Run();
Then I hit https://localhost:5001/swagger and I get the SwaggerUI and a little WebAPI Tester:
Anuraj has a great blog where he goes deeper and pokes around David Fowlers GitHub and creates a minimal WebAPI with Entity Framework and an in-memory database with full OpenAPI support. He put the source at at https://github.com/anuraj/MinimalApi so check that out.
Bipin Joshi did a post also earlier in June and explored in a bit more detail how to hook up to real data and noted how easy it was to return entities with JSON output as the default. For example:
app.UseEndpoints(endpoints => { endpoints.MapGet("/api/employees",([FromServices] AppDbContext db) => { return db.Employees.ToList(); }); ...snip... }
That's it! Very clean.
Dave Brock did a tour as well and did Hello World in just three lines, but of course, you'll note he used WebApplication.Create while you'll want to use a Builder as seen above for real work.
var app = WebApplication.Create(args); app.MapGet("/", () => "Hello World!"); await app.RunAsync();
Dave does point out how nice it is to work with simple models using the C# record keyword which removes a LOT of boilerplate cruft.
Check this out!
var app = WebApplication.Create(args); app.MapGet("/person", () => new Person("Scott", "Hanselman")); await app.RunAsync(); public record Person(string FirstName, string LastName);
That's it, and if you hit /person you'll get back a nice JSON WebAPI with this result:
{ firstName: "Scott", lastName: "Hanselman" }
Dig even deeper by checking out Maria Naggaga's presentation in June that's on YouTube where she talks about the thinking and research behind Minimal APIs and shows off more complex apps. Maria also did another great talk in the same vein for the Microsoft Reactor so check that out as well.
Is this just about number of lines of code? Have we moved your cheese? Will these scale to production? This is about enabling the creation of APIs that encapsulate best practices but can give you the "middleware-like" performance with the clarity and flexibility that was previous available with all the ceremony of MVC.
Here's some more resources:
David Fowler's GitHub demo https://github.com/davidfowl/dotnet6minimalapi/tree/main/Dotnet6_Minimal_API
A ToDo API as a Minimal API https://github.com/davidfowl/CommunityStandUpMinimalAPI
Exploring what Integration Testing looks like in a .NET 6 world by Martin Costello https://github.com/martincostello/dotnet-minimal-api-integration-testing I'll be exploring Martin's codebase next!
Have fun! Lots of cool things happening this year, even in the middle of the panini. Stay safe, friends.
Sponsor: Pluralsight helps teams build better tech skills through expert-led, hands-on practice and clear development paths. For a limited time, get 50% off your first month and start building stronger skills.
© 2021 Scott Hanselman. All rights reserved.
Exploring a minimal Web API with ASP.NET Core 6 published first on https://deskbysnafu.tumblr.com/
0 notes
Text
Exploring a minimal Web API with ASP.NET Core 6
I write about minimal Web APIs in 2016 and my goal has always been for "dotnet server.cs" to allow for a single file simple Web API. Fast forward to 2021 and there's some great work happening again in the minimal API space!
Let's do a 'dotnet new web' with the current .NET 6 preview. I'm on .NET 6 preview 7. As mentioned in the blog:
We updated .NET SDK templates to use the latest C# language features and patterns. We hadn’t revisited the templates in terms of new language features in a while. It was time to do that and we’ll ensure that the templates use new and modern features going forward.
The following language features are used in the new templates:
Top-level statements
async Main
Global using directives (via SDK driven defaults)
File-scoped namespaces
Target-typed new expressions
Nullable reference types
This is pretty cool. Perhaps initially a bit of a shock, but this a major version and a lot of work is being done to make C# and .NET more welcoming. All your favorite things are still there and will still work but we want to explore what can be done in this new space.
Richard puts the reasoning very well:
The templates are a much lower risk pivot point, where we’re able to set what the new “good default model” is for new code without nearly as much downstream consequence. By enabling these features via project templates, we’re getting the best of both worlds: new code starts with these features enabled but existing code isn’t impacted when you upgrade.
This means you'll see new things when you make something totally new from scratch but your existing stuff will mostly work just fine. I haven't had any trouble with my sites.
Let's look at a super basic hello world that returns text/plain:
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); if (app.Environment.IsDevelopment()){ app.UseDeveloperExceptionPage(); } app.MapGet("/", () => "Hello World!"); app.Run();
Slick. Note that I made line 3 (which is optional) just be one line to be terse. Not needed, just trying on these new shoes.
If we make this do more and support MVC, it's just a little larger. I could add in app.MapRazorPages() if I wanted instead of MapControllerRoute, which is what I use on my podcast site.
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
Back to the original Web API one. I can add Open API support by adding a reference to Swashbuckle.AspNetCore and then adding just a few lines:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.MapGet("/", () => "Hello World!"); app.UseSwaggerUI(); app.Run();
Then I hit https://localhost:5001/swagger and I get the SwaggerUI and a little WebAPI Tester:
Anuraj has a great blog where he goes deeper and pokes around David Fowlers GitHub and creates a minimal WebAPI with Entity Framework and an in-memory database with full OpenAPI support. He put the source at at https://github.com/anuraj/MinimalApi so check that out.
Bipin Joshi did a post also earlier in June and explored in a bit more detail how to hook up to real data and noted how easy it was to return entities with JSON output as the default. For example:
app.UseEndpoints(endpoints => { endpoints.MapGet("/api/employees",([FromServices] AppDbContext db) => { return db.Employees.ToList(); }); ...snip... }
That's it! Very clean.
Dave Brock did a tour as well and did Hello World in just three lines, but of course, you'll note he used WebApplication.Create while you'll want to use a Builder as seen above for real work.
var app = WebApplication.Create(args); app.MapGet("/", () => "Hello World!"); await app.RunAsync();
Dave does point out how nice it is to work with simple models using the C# record keyword which removes a LOT of boilerplate cruft.
Check this out!
var app = WebApplication.Create(args); app.MapGet("/person", () => new Person("Scott", "Hanselman")); await app.RunAsync(); public record Person(string FirstName, string LastName);
That's it, and if you hit /person you'll get back a nice JSON WebAPI with this result:
{ firstName: "Scott", lastName: "Hanselman" }
Dig even deeper by checking out Maria Naggaga's presentation in June that's on YouTube where she talks about the thinking and research behind Minimal APIs and shows off more complex apps. Maria also did another great talk in the same vein for the Microsoft Reactor so check that out as well.
Is this just about number of lines of code? Have we moved your cheese? Will these scale to production? This is about enabling the creation of APIs that encapsulate best practices but can give you the "middleware-like" performance with the clarity and flexibility that was previous available with all the ceremony of MVC.
Here's some more resources:
David Fowler's GitHub demo https://github.com/davidfowl/dotnet6minimalapi/tree/main/Dotnet6_Minimal_API
A ToDo API as a Minimal API https://github.com/davidfowl/CommunityStandUpMinimalAPI
Exploring what Integration Testing looks like in a .NET 6 world by Martin Costello https://github.com/martincostello/dotnet-minimal-api-integration-testing I'll be exploring Martin's codebase next!
Have fun! Lots of cool things happening this year, even in the middle of the panini. Stay safe, friends.
Sponsor: Pluralsight helps teams build better tech skills through expert-led, hands-on practice and clear development paths. For a limited time, get 50% off your first month and start building stronger skills.
© 2021 Scott Hanselman. All rights reserved.
Exploring a minimal Web API with ASP.NET Core 6 published first on http://7elementswd.tumblr.com/
0 notes
Text
React Native with Push Notifications and Firebase - Part 3 of 5
In this five-part tutorial we'll see how we can create a sample React Native app (you might call it a "Hello World" or "boilerplate") that will be capable of receiving Push Notifications using Firebase. Such guide could be a great headstart for React Native beginners, yet also for those intermediate or experienced developers who want to know more about push notifications: how they work, what are their best usage scenarios and how much they can be an improvement for almost any mobile app. For the sake of simplicity this tutorial has been splitted into multiple parts, each one dedicated to a specific sub-topic: Part 1 of 5: Understanding Push Notifications, in which we'll try to understand what push notifications actually are and the impact they could have (when used properly) on a typical client-server app. Part 2 of 5: Setup React Native and Firebase, where we'll deal with the installation and configuration of our whole development stack: React Native, the Firebase SDK and the Visual Studio Code environment, together with the required settings to get our app ready to work with Android and iOS. Part 3 of 5: Configure the Firebase Service, in which we'll create the Firebase Project and configure the Firebase Push Notification Services to ensure that our React Native app will be able to receive push notifications through the Firebase API on any Android and iOS device. Part 4 of 5: Design and Test the React Native UI, where we'll test our front-end skills by laying out a React-Native UI in order to make our app actually able to receive push notifications and send HTTP requests to the server to remotely keep track of our actions - and possibly fire subsequent push notifications to other clients. Part 5 of 5: Server-Side Handler, in which we'll use ASP.NET Core to create a sample, lightweight web server that will be able to receive HTTP requests issued by the clients and/or feed them with push notifications through the Firebase API. In this third post we'll see how we can configure the Firebase Service for Android and iOS environments.
Create the Firebase project
Now that our app is up and running, we just need to configure the Firebase Service to ensure that our React Native application will be able to receive push notifications through the Firebase API. Create a Google account (if you don't have one already). Navigate to the Google Firebase website. Click to the Get Started button. Add a new Firebase project.

Configuring the Firebase Service
Once the project is ready, you'll be asked to add one or more app on it. More specifically, we need to add two apps: one for Android and one for iOS. Firebase Android App Add a new Android app by clicking on the android logo and fill in the relevant values.

Once done, you'll be given the chance to download a google-services.json file containing the required configuration to run Firebase on the Android version of your React Native app: download and save it within the /android/app/ folder of your React Native app, just as explained and illustrated on the web page itself:

Download the google-services.json file and placing it in the appropriate folder, then get ready to go ahead. Steps 3 and 4 can be skipped, as we already performed their relevant tasks in the part 2 of this guide: for this reason, just click the Next button a couple times press the Next button a couple times to enter into the Run your app to verify installation phase. This is basically a ping test that Firebase will do to verify that your app can connect to its API, thus ensuring that the SDK has been installed correctly. As soon as the test runs, you will see a grey message saying that Firebase is trying to check for your app presence. Leave the web page open, switch to Visual Studio Code and run your React Native app in debug mode. If you did everything correctly, the app should run with no issues and show the "Welcome to React" sample view on your emulator (or test phone) screen:

Right after that, switch back to the Firebase testing page and ensure that the app has been detected there as well. If everything is OK you should be able to see the following green message:

Our Firebase Android App is complete. Now we need to do the same with the iOS App. Firebase iOS App Creating the iOS app is rather similar to the Android process we've just dealt with. Go back to the project dashboard, then click the Add app button to add a new iOS app: click on the iOS logo when asked to choose a platform and then fill in the relevant values to the Add Firebase to your iOS app form, just like we did with the Android app.

Once you've done, click Register App and then Next to continue to the step 2, wher e you'll be given the chance to download a GoogleService-info.plist file containing the required configuration to run Firebase on the iOS version of your React Native app: download and save it within the /ios// folder of your React Native app, the same folder where the Info.plist file is. If you use XCode, you can take the picture shown on the Firebase web page as a useful reference:

Again, the next two steps (3 and 4) can be skipped, as we already performed the mentioned tasks in the part 2 of this guide: for this reason, just click the Next button a couple times to enter into the Run your app to verify installation phase. This is basically a ping test that Firebase will do to verify that your app can connect to its API, thus ensuring that the SDK has been installed correctly. As soon as the test runs, you will see a grey message saying that Firebase is trying to check for your app presence. Leave the web page open, switch to your Mac's XCode and run your React Native app in debug mode.
Conclusion
That's it! If everything went good, it means we've successfully created our Firebase project, the Android and iOS Firebase app, and tested our connection between them and our React Native app... meaning that we can already receive push notifications on our device(s)! Now we need to deal with our React-Native UI in order to make our app actually able to receive push notifications. Part 4 of 5: Implement the React Native UI Read the full article
0 notes
Text
Build a Basic Android App with Xamarin and Visual Studio
Are you a .NET developer that has always wanted to make a mobile application? Or maybe you have tried building native mobile apps with Android or iOS but didn’t like the languages? Well then, you are in luck! The .NET world has been blessed with Xamarin; a set of tools that lets you build mobile apps for Android, iOS, and Windows within Visual Studio.
Xamarin has two main flavors: Xamarin platform (Xamarin.iOS and Xamarin.Android) and Xamarin.Forms. With Xamarin.Forms a vast majority of your business logic and user interface can be written within one shared project that produces fully functioning apps on all 3 of the iOS, Android and the Windows (UWP) operating systems. Xamarin platform, on the other hand, is very much platform-specific work and is more akin to writing native apps but with C#.
In this tutorial, I’ll be looking more closely at the Xamarin platform and the Android operating system toolset known as Xamarin.Android. The overall aim is to enable you to create a simple native Android app with basic user authentication included.
SET UP VISUAL STUDIO AND YOUR ENVIRONMENT
To follow along you’ll need a copy of Visual Studio, plus the ‘Mobile development with .NET’ workload. You can either enable this feature from first installation of Visual Studio or access it from the ‘Tools -> Get Tools and Features…’ menu item:
When testing and running your app you have the choice of doing so with either an Android emulator running on your development machine, or by directly connecting to an existing Android device. There’s no right option here and different developers prefer different form factors. If you choose the former option, you’ll need to ensure once you’ve selected the workload that on the right-hand pane (‘Installation details’) the checkboxes for Intel Hardware Accelerated Execution Manager and Google Android Emulator are selected (as seen above).
VERIFY YOUR ANDROID ENVIRONMENT IN VISUAL STUDIO
To verify everything installed properly and was configured correctly, go to ‘Tools -> Options -> Xamarin -> Android Settings’ and check your Java Development Kit Location and Android SDK Location paths are valid (i.e. have a green tick):
If either are missing you’ll have to manually install the Java Development Kit or Android SDK respectively.
CREATE A XAMARIN APP
Start by creating a new project and select the ‘Android App (Xamarin)’ master template (found under the Android menu). On the next page you’ll want to pick the ‘Single View App’ option as it is a great starter template to work from.
With regards to the Minimum Android Version, this is something down to your personal choice as the developer. There is a trade-off here between being able to access the latest and greatest API features in newer versions and supporting your customers that have older versions. To help you make this decision, Google publishes platform version distribution data they collect as part of their Distribution dashboard on a fairly regular cadence. My personal preference is between 5.0 or 6.0 depending on if this is an app for public consumption or a commissioned app for corporate phones only (i.e. they will likely have the latest updates); in this example I’ve gone with the latter. Note this version differs from the Target Android Version and that should always be set to the latest released SDK version, as anything less won’t be accepted into the Google Play store.
Once you’ve got this created all that’s left is to import the required NuGet packages. For this tutorial you will need
Xamarin.OpenId.AppAuth.Android - To Authenticate the user you will be using OpenID Connect standard (an enhancement of OAuth 2.0). The easiest way to implement client code that abides by this specification is by using the AppAuth client SDK for Android, and helpfully Xamarin has ported a package of this functionality available for you to use.
System.IdentityModel.Tokens.Jwt - The method of authentication here uses JSON Web Tokens. To extract the data needed from these tokens you’ll need this package.
Additionally, you’ll need these two packages as well as they’re relied upon by AppAuth
Xamarin.Android.Support.v4
Xamarin.Android.Support.CustomTabs
FAMILIARIZE YOURSELF WITH THE XAMARIN PROJECT
If you’ve never worked with Android before, one of the key principles to get your head around is the concept of an Activity. Activities are components used to display your user interface; in their most basic form, you can think of Activities as being equal to pages in an app that the user can navigate between. An Activity in code is represented by a class, however like a page in ASP.NET you can (and almost always will) associate an XML-based layout file (a .axml file) with it for a displayable design. All new projects create a ‘MainActivity.cs’ and ‘activity_main.axml’ file to start with as the first Activity (i.e. page) to run upon opening the app. This can be changed to any other Activity by utilisation of the property MainLauncher = true within the Activity attribute of the class.
Resources are designed to be handled within their own directory and follow a somewhat strict naming convention. I’d strongly recommend storing as much of your resources as is feasible in this directory since it simplifies the reuse of these variables for your ongoing android app development. In the ‘values’ directory of the Resources directory is where you will find files with specific purposes
Strings.xml - Hosts all user facing strings. This one is especially important to use as it enables you to localise your strings for a global audience.
Styles.xml - Where you’ll find the attributes for styling your design objects; think of it like a CSS file.
Colors.xml - A place to store references to the colours you use most frequently as part of your styling.
Dimens.xml - As the name might imply, where you define set dimensions for your app’s layout.
The other notable directories don’t follow any naming convention for their files, but they must contain certain file types
Layout - Location for storing your .axml files. These files define full Activity layouts, layout components that you programmatically generate and populate, layouts of dialog (alert) boxes, etc.
Menu - Where you’ll find definitions of menus and their items. These are .xml files that have menu as the root element and item child elements, of which can be grouped together with group elements. Most common menus you’ll encounter are the overflow menu (from the three vertical dots button) or the navigation menu (from the home ‘hamburger’ button).
Mipmap - Where you want to define images that need to be scaled depending on the screen density, i.e. those referenced by other apps, and not used internally. The app’s icon is the most common content you would put in the mipmap directories.
Drawable - Not standard in a default project template, but can be created yourself. This is where you store your images/drawable content to be used within the app, e.g. splash screen, custom progress bar designs, icons used within the app, etc.
Lastly, if you have any raw content files that you want to use as part of your application (e.g. a text or font file), then the Assets directory is where to place them. As Assets these files will be deployed with your app for you to access with the Asset Manager.
To learn more about Assets and Resources and how to use them, there are handy ‘About’ text files in each directory of a newly created project.
ADD USER AUTHENTICATION TO XAMARIN WITH OPENID CONNECT
Most apps these days require some form of user identification to enable the developer to offer bespoke experiences and in turn enable the user to keep their data across devices/installations. In addition to this there’s the matter of access control that might be useful to authorize a subset of users for extra functionality. Naturally this can be quite the laborious task, especially if you’re in the business of creating apps and you’ll need a new system for every single one. Thankfully with Okta you can set up an application in mere minutes and then all the hard work is done for you! The Okta service is OAuth 2.0 compliant and a certified OpenID Connect Provider, and so works perfectly with the AppAuth client SDK for all your authentication and authorization needs.
Set Up your Okta Application
Firstly, you should set up a new application in your Okta account for this project. If you’ve not got one yet, it’s really easy to create a new forever-free developer account.
Once that’s complete and you’ve logged in to the developer dashboard, take a note of the Org URL as we’ll need that later:
From the dashboard go to the ‘Applications’ tab and from there ‘Add Application’. You’re creating a native Android application, so it’s best to pick the ‘Native’ platform template.
From this page add a name for your application and leave everything else as default. Once saved take note of your Login redirect URIs and Client ID as you’ll be needing these next.
So you can use these three values from Okta with ease in the future, I would recommend putting them in their own static class within a new directory for the authentication logic:
public static class Configuration { public const string ClientId = "{yourClientId}"; public const string LoginRedirectUri = "{yourRedirectUri}"; public const string OrgUrl = "https://{yourOktaDomain}"; }
Create the Authentication Provider
Let’s get the boilerplate code out of the way. You need to configure the app to inform it of your redirect URI scheme. The scheme is your login redirect URI (in standard reverse domain name form) without the path. For example, from the above screenshot my scheme would be ‘com.oktapreview.dev-123456’.
The easiest way to do this is to insert the below intent filter snippet into your AndroidManifest.xml file in the Properties folder of your solution. Add the following XML within the Application tag and change the scheme value to your own:
<activity android:name="net.openid.appauth.RedirectUriReceiverActivity"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="{yourRedirectRriScheme}" /> </intent-filter> </activity>
You also need to define the model for the result of your authorization with a simple class. While I won’t be using all the values I’ve written below within the code, I will show how to populate them for you to use after. As this is part of your application’s model, create a folder called Models and add an AuthorizationResult.cs class inside it. Then, add the following code:
public class AuthorizationResult { public string AccessToken { get; set; } public string IdentityToken { get; set; } public bool IsAuthorized { get; set; } public string RefreshToken { get; set; } public string Scope { get; set; } }
Android doesn’t have a global state for you to work with, and so if you want to pass simple values between activities, the best way to do this is with the Extras functionality on the Intent object. An Intent is a predefined class in Android and another core concept to understand. It is the abstraction of an operation to be performed (i.e. your ‘intentions’), and to navigate forward to another activity you need to create an instance of this class with which activity you ‘intend’ to go to. The Extras properties on the Intent object are in effect just a dictionary of keys to object values and are accessed by Put and typed Get methods.
While these methods keep the usage relatively clear and easy I personally like to keep all access to them within their own class (to be precise, an extensions class), to maintain a better separation of concerns. This is extremely useful as you don’t need to access the keys across classes and can assure type safety when putting and getting these values. In your authorization provider you’ll be wanting to: store the AuthState , be able to check whether it’s there, and return it if it is. Create a new folder called Extensions in the root of the solution. Then add a new class called IntentExtensions.cs . Make the class public and static , then add the following code inside the class:
public const string AuthStateKey = "authState"; public static string GetAuthStateExtra(this Intent intent) { return intent.GetStringExtra(AuthStateKey); } public static bool HasAuthStateExtra(this Intent intent) { return intent.HasExtra(AuthStateKey); } public static void PutAuthStateExtra(this Intent intent, AuthState authState) { intent.PutExtra(AuthStateKey, authState.JsonSerializeString()); } public static bool TryGetAuthStateFromExtra(this Intent intent, out AuthState authState) { authState = null; if (!intent.HasAuthStateExtra()) { return false; } try { authState = AuthState.JsonDeserialize(intent.GetAuthStateExtra()); } catch (JSONException) { return false; } return authState != null; }
Now it’s time to define the authorization provider, AuthorizationProvider.cs in the Authentication folder you created before for the Configuration.cs class. Firstly, remove all the using statements inside the newly created class, then declare the configuration as static readonly variables:
private static readonly Uri ConfigurationEndpoint = Uri.Parse($"{Configuration.OrgUrl}/oauth2/default/.well-known/openid-configuration"); private static readonly string[] Scopes = new[] { "openid", "profile", "email", "offline_access" };
The configuration endpoint is a standard in OpenID as the discovery endpoint to find all that’s supported. Note here I’ve written this is using the ‘default’ provider name. If you have a different provider, you’ll want to change this here. Also note that this is using the Android.Net flavour of the Uri class, and not the System version - you’ll need to add the former to your usings or fully qualify the type for this to work. The Scopes variable, like any other OpenID system, defines what we’re authorized to access.
Next you should declare your member variables:
private AuthorizationRequest authorizationRequest; private PendingIntent completedIntent; private AuthState authorizationState; private readonly AuthorizationService authorizationService; private readonly Context context; private readonly TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
The authorization request and completed intent are parameters created for use in making the authorization call. I’ve written them as global variables here to minimise the amount of passing parameters into different methods.
The authorizationState variable as it’s named defines the current given authorization state.
The authorizationService variable contains an instance of the authorization service.
The context variable here is of the calling activity, so you can reference it when necessary.
Finally, the taskCompletionSource enables you to make all these calls asynchronously and then return once complete.
Now you should define the values of these readonly variables in your constructor, and declare the public methods your code will call:
public AuthorizationProvider(Context context) { authorizationService = new AuthorizationService(context); this.context = context; } public async Task<AuthorizationResult> SignInAsync() { ... } public void NotifyCallback(Intent intent) { ... }
The SignInAsync method is as you might have guessed an asynchronous method to sign a user in. This returns the AuthorizationResult class you wrote earlier. NotifyCallback on the other hand is for the calling activity, once it has returned from the external sign in page, to call back to the authorization provider and let it know it’s done. The sign in method I’ve broken out into multiple subroutines, and looks like this:
AuthorizationServiceConfiguration serviceConfiguration = await AuthorizationServiceConfiguration.FetchFromUrlAsync(ConfigurationEndpoint); BuildAuthorizationRequest(serviceConfiguration); BuildCompletedIntent(serviceConfiguration); return await RequestAuthorization();
In this you have defined the service configuration, built the authorization request and the intent to call once the authorization has been completed, and then await the request of authorization. To build the authorization request is as follows:
private void BuildAuthorizationRequest(AuthorizationServiceConfiguration serviceConfiguration) { AuthorizationRequest.Builder builder = new AuthorizationRequest.Builder( serviceConfiguration, Configuration.ClientId, ResponseTypeValues.Code, Uri.Parse(Configuration.LoginRedirectUri)); builder.SetScope(string.Join(" ", Scopes)); authorizationRequest = builder.Build(); }
The job of this method is to abstract away the AuthorizationRequest.Builder work and create the request. Next you need to build the Intent for once the operation has completed:
private void BuildCompletedIntent(AuthorizationServiceConfiguration serviceConfiguration) { Intent intent = new Intent(context, typeof(MainActivity)); intent.PutAuthStateExtra(new AuthState()); completedIntent = PendingIntent.GetActivity(context, authorizationRequest.GetHashCode(), intent, 0); }
The ‘intention’ that you want to perform here is to return to your MainActivity with a new AuthState attached. Lastly in this flow is to deal with executing the request:
private async Task<AuthorizationResult> RequestAuthorization() { authorizationService.PerformAuthorizationRequest(authorizationRequest, completedIntent); await taskCompletionSource.Task; return new AuthorizationResult() { AccessToken = authorizationState?.AccessToken, IdentityToken = authorizationState?.IdToken, IsAuthorized = authorizationState?.IsAuthorized ?? false, RefreshToken = authorizationState?.RefreshToken, Scope = authorizationState?.Scope }; }
As PerformAuthorizationRequest is synchronous and returns void, the code awaits upon the taskCompletionSource member, knowing it will only ever be set once a response has been retrieved. At this very same point you know the authorization state will be populated (if everything succeeded), and so you can return their values as part of the AuthorizationResult.
The second public method NotifyCallback , as I mentioned before, is what you want the MainActivity class to call back on, once your above completedIntent is run. In this method you want to verify the response, update the state appropriately, and if successful, perform a token exchange request:
if (!intent.TryGetAuthStateFromExtra(out authorizationState)) { taskCompletionSource.SetResult(false); return; } AuthorizationResponse authorizationResponse = AuthorizationResponse.FromIntent(intent); AuthorizationException authorizationException = AuthorizationException.FromIntent(intent); authorizationState.Update(authorizationResponse, authorizationException); if (authorizationException != null) { taskCompletionSource.SetResult(false); return; } authorizationService.PerformTokenRequest(authorizationResponse.CreateTokenExchangeRequest(), ReceivedTokenResponse);
Here you can see in the fail cases I set the result of taskCompletionSource to false, and that will unblock the RequestAuthorization method above. Also, the PerformTokenRequest method takes in a delegate, ReceivedTokenResponse , to be run once it has completed. This method is as follows:
private void ReceivedTokenResponse(TokenResponse tokenResponse, AuthorizationException authorizationException) { authorizationState.Update(tokenResponse, authorizationException); taskCompletionSource.SetResult(true); }
At this point you should have all the authorization data you need, and so can update the state appropriately (where you’ll find the values to return from the sign in method) and set the result to unblock the taskCompletionSource task.
IMPLEMENT AUTHENTICATION INTO YOUR XAMARIN INTERFACE
As a clean-up if you so wish, feel free to remove all references to the ‘Floating Action Bar’ (also written as ‘FAB’) within the main activity class/axml files as they’re unnecessary bloat at this stage.
To allow the user to sign in you now need to implement this functionality into the UI. Given the default design, the most intuitive way to do this would be to add an item to the overflow menu in the top right corner. You can do this by editing the menu_main.xml file in the ‘Resources -> menu’ folder, and adding this item as a child of the menu tag:
<item android:id="@+id/action_signin" android:orderInCategory="100" android:title="@string/action_signin" app:showAsAction="never" />
With this code you’ve created a new option with a title to be defined in the string resources file. As mentioned before in Android it’s best practice to put all user facing text in the string resources file. To declare this data, edit the strings.xml file in the ‘Resources -> values’ folder and add these lines:
<string name="action_signin">Sign In</string> <string name="welcome_message_format">Hi, %1$s!</string>
Not only have I declared a string for the ‘Sign In’ button here, but I’ve also added above a string for a welcome message to the user once they have signed in. The equivalent to the C# code of this string would be “Hi, {0}!”`, where the placeholder is of type string.
Note with all updates to these Resources-based files, the Resource.designer.cs class will automatically be regenerated with new IDs for each object you’ve created, that can be referenced within your code. If this isn’t working for a particular file then select it in Solution Explorer and look at the Properties window. Make sure the CustomTool property is set to the value MSBuild:UpdateGeneratedFiles , as this is likely missing and preventing the designer file from recognising it as a resource.
Next add a ProgressBar to the existing activity_main.axml layout file:
<ProgressBar android:id="@+id/signin_progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:paddingBottom="12dp" android:visibility="gone" />
This ProgressBar (or spinner, as the case is), has an ID you can reference with code, and is set up to sit around the centre of the screen. The visibility is set to gone for now, but once your authorization code is running you can set it to visible and inform the user that the app is busy.
Now you have a button to open authentication and a progress spinner to inform the user the app is busy, it’s time to use them. Within your MainActivity class add the following property to the Activity attribute (above the class header):
LaunchMode = LaunchMode.SingleTask
This property ensures there is only one instance of the MainActivity class, and you don’t keep opening new ones. Once you’ve done this, add a static member variable for the AuthorizationProvder you wrote above and create an instance of it within the existing override of the OnCreate method. Note this should be done after the existing code within the method:
private static AuthorizationProvider authorizationProvider; protected override void OnCreate(Bundle savedInstanceState) { ... authorizationProvider = new AuthorizationProvider(this); }
Next, override the OnNewIntent method. The purpose of this is when a new intent of this class is created (i.e. when the external sign in window returns), you call the NotifyCallback method from the AuthorizationProvider . Also included in this is a quick check to make sure it’s the expected flow:
protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); if (intent != null && intent.Data.Path.Equals("/callback", StringComparison.OrdinalIgnoreCase)) { authorizationProvider.NotifyCallback(intent); } }
Now add the code behind the menu item you added. In the existing override of the OnOptionsItemSelected method, add an if statement with a call to a new method that will handle the sign in process as follows:
if (id == Resource.Id.action_signin) { OnSignInAttempted(); return true; }
This new method will start by making the ProgressBar you added moments ago visible; to retrieve any component from the layout file, use the generic method FindViewById and enter the component’s ID as its argument. After this, make a call to the SignInAsync method and await its result. Once the call has returned the result is then verified as authorized. If this authorization failed for whatever reason an error dialog appears, and the progress spinner disappears again. I’ll leave detailing the success case for now as you still need somewhere to go in that instance:
private async void OnSignInAttempted() { ProgressBar signInProgress = FindViewById<ProgressBar>(Resource.Id.signin_progress); signInProgress.Visibility = ViewStates.Visible; AuthorizationResult authorizationResult = await authorizationProvider.SignInAsync(); if (!string.IsNullOrWhiteSpace(authorizationResult.AccessToken) && authorizationResult.IsAuthorized) { // Placeholder: Success case } else { // Display an error to the user AlertDialog authorizationErrorDialog = new AlertDialog.Builder(this) .SetTitle("Error!") .SetMessage("We were unable to authorize you.") .Create(); authorizationErrorDialog.Show(); signInProgress.Visibility = ViewStates.Gone; } }
When the user is authenticated you should redirect them to the next page of your experience. If you recall earlier each page is represented by an Activity, and so you need to create a new one now.
To start, within the ‘Resources -> layout’ folder you’ll need to create the new activity layout file “activity_dashboard.axml”. The easiest way to do this is by going to the New Item… option in the context menu and selecting the ‘Android Layout’ template. Within your new layout file add a simple TextView component to display text like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:id="@+id/welcome_message" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </LinearLayout>
In this snippet you have a TextView component with a referenceable ID that’s centered in the middle of the page, of which will display a welcome message. Next create a corresponding activity class ‘DashboardActivity’ by means of the ‘New Item…’ option in the context menu from the project in the solution explorer and selecting the ‘Activity’ template. To link this class to its layout file, you need to call the SetContentView function in the generated OnCreate() method (under the inherited base method invocation):
SetContentView(Resource.Layout.activity_dashboard);
To personalise your welcome message, you’ll want to pass the user’s name to your new activity. If you remember earlier the best way to do this was with Extras on the intent, and you created an extensions class to handle this. Like before, add new methods for ‘Put’ and ‘Get’ of a ‘name’ extra in the IntentExtensions.cs file you created above:
private const string NameKey = "Name"; public static void PutNameExtra(this Intent intent, string name) { intent.PutExtra(NameKey, name); } public static string GetNameExtra(this Intent intent) { return intent.GetStringExtra(NameKey); }
Now using this extended functionality, after the call to SetContentView you did in the OnCreate() method, retrieve the user’s name and set the TextView component’s text appropriately:
string name = Intent.GetNameExtra(); TextView welcomeMessage = FindViewById<TextView>(Resource.Id.welcome_message); welcomeMessage.Text = Resources.GetString(Resource.String.welcome_message_format, name);
In this extract, upon retrieving the TextView instance its value is set to your welcome message, of which is created using the Android Resources equivalent of string.Format() .
With this your dashboard activity is complete, and you now need to call to it. In the placeholder for the success case I left open from the OnSignInAttempted method, you can achieve this by adding the following code:
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jsonToken = tokenHandler.ReadJwtToken(authorizationResult.IdentityToken); IEnumerable<Claim> claims = jsonToken?.Payload?.Claims; string name = claims?.FirstOrDefault(x => x.Type == "name")?.Value; Intent dashboardIntent = new Intent(this, typeof(DashboardActivity)); dashboardIntent.PutNameExtra(name); StartActivity(dashboardIntent); Finish();
The first block reads the token and retrieves the user’s name (if it exists). In the second a new Intent is created for the dashboard activity, the user’s name is stored in this Intent using your above-defined extension method, and then the activity is started (i.e. navigated to). To prevent the user from navigating back to this page afterwards, the code ends by calling the Finish() method.
RUN YOUR ANDROID APP
Now it’s time to launch your application using your chosen device!
If you’re debugging using the emulator this should be as simple as hitting F5 of which will first open and load the emulator, and then the code will deploy to it. As a side note you don’t need to close the emulator between run/debug attempts, as it only needs to redeploy the app.
If you’re debugging using a device that hasn’t been used for this purpose before, you’ll need to set the device up first. Do this by enabling developer options and within the new menu, switching on ‘Android debugging’ under the ‘Debugging’ header. After this, just plug the device in, accept the dialog on your device confirming this is a safe debugging connection, and you should be able to deploy and run your app with F5. Note physical devices have higher precedence than the emulator and will switch to it as the default debugging option when plugged in.
Once your app has deployed and loaded up, you’ll be greeted by the default single page template. Open the menu in the top right corner to sign in, and once you’ve entered your details you should return to this page with the spinning progress bar before automatically being sent to the dashboard page with your welcome message:
Source: https://developer.okta.com/blog/2018/12/27/build-a-basic-android-app-with-xamarin-and-visual-studio
0 notes
Text
ASP.NET Zero is an Effective Solution for Creating Web and Mobile Apps
Software outsourcing is a way to deploy the organization internal work to some external agency. These agencies could be situated overseas or in the same geographical constant. Hiring an outsource partner is tricky and when a company decides of hiring the external support, its choice of finding a suitable outsourcing partner depends on several crucial considerable thoughts. Outsourcing is not merely a signed agreement between two parties but it could be termed as the growing relation between the client and the outsourced agency for better future project and expanding prospects.
ASP.NET Zero is a ready-made solution that comes with all out-of-the-box functionality for most standard web and Mobile application solution. In fact, this is a good start for the project where the main functionality is ready and you do not need to spend time developing basic functionality and you can immediately proceed to developing business logic and unique solutions.
ASP.NET Zero Features
1. It provides a layered, well-defined and documented architectural model. 2. It's give the predefined scalation / architecture for the application 3. It provides a strong infrastructure and development model for modularity, multi-tenancy, caching, background jobs, data filters, setting management, domain events, unit & integration testing . You focus on your business code and don't repeat yourself! 4. It's based on the open-source and community-driven ABP framework. 5. It makes your daily development easier by providing base classes and infrastructure, and automates your repeated tasks. 6. ASP.NET Zero uses Metronic as the UI theme. 7. Metronic is one of the world's most popular, strongest and richest UI themes, probably even the first. 8. Version and feature management UI 9. Notification system along with real time chat and emails 10. Provides User profile, account linking, social logins 11. Many built-in solutions (extension libraries) for dependency injection, logging, caching, localization, configuration and so on. These are independent from the
ASP.NET Core and usable for any type of application.
1. Repositories (that can be used as is without developing custom extensions) 2. Unit of Work (application service can be decorated with a transactional aspect) 3. Server-side validation (via data annotations or custom validators) 4. Dynamic Web API controllers (automatically-generated web API layer for your application layer) 5. Background Services (jobs) 6. Real Time Services (SignalR integration) 7. Xamarin mobile application
Provide Multiple solution for the Web/Mobile development
1. ASP.NET Core 2.x and Angular 7.x based Single-Page Application (SPA) solution for your web application (with .NET Framework 4.6.1 / .NET Core options) 2. ASP.NET Core 2.x and jQuery based solution for your web application (with .NET Framework 4.6.1 / .NET Core options) 3. ASP.NET MVC 5.x, Web API and AngularJS 1.x based Single-Page Application (SPA) solution for your web application 4. ASP.NET MVC 5.x and jQuery based solution for your web application 5. XAMARIN mobile application integrated with the backend solution. 6. ASP.NET Core/MVC based application for your public web site
Multi-tenancy
1. Tenant and Edition (package) management for SaaS applications 2. Subscription management & recurring payments 3. PayPal & Stripe integration 4. Dashboard for edition, tenant & income statistics 5. Single database, database per tenant and hybrid database support 6. Custom tenant logo and CSS support 7. Can work in multi-tenant and single-tenant modes
Authentication & Authorization
1. Based on ASP.NET Identity Framework 2. User & role management pages 3. Hierarchical organization units system to group users and entities 4. User login, register, password-reset and email validation pages 5. User, role and permission based flexible authorization 6. User and Tenant impersonation 7. User account linking 8. Two Factor Authentication (Email, SMS, Google Authenticator) 9. User Lockout 10. LDAP/Active Directory login support 11. Active Directory Federation Service (ADFS) Authentication 12. Social media logins (Facebook, Twitter, Google+ and Microsoft Account implemented) 13. OpenId Connect Authentication 14. Log and show all login attempts for users 15. Password complexity settings 16. Automatic Cross-Site Request Forgery (CSRF) protection 17. IdentityServer4 integration
Rapid Application Development
1. Templating support to generate customized code
Mobile Application
1. Cross-platform (iOS & Android) Xamarin mobile application 2. Integrated with the backend API 3. Provides infrastructure for common development tasks
Dynamic Ui Localization
1. Fully localized UI 2. Can add, remove and translate languages on UI 3. RTL and LTR support 4. English, Chinese, German, French, Italian, Russian, Portuguese (Brazil), Spanish (Mexico), Spanish (Spain), Turkish and Arabic localizations are included
Setting Management
1. Host & tenant-specific setting pages 2. Hierarchical setting management infrastructure 3. Easily configurable
Solid Architecture
1. Clean source code in a well-defined solution structure 2. Layered & modular architecture 3. Domain Driven Design implementation 4. Dependency injection everywhere 5. Validation 6. Logging 7. Exception handling 8. Caching 9. Automatic audit/security logging 10. Automatic database connection management and unit of work implementation 11. Pre-configured to deploy as Docker containers 12. Application functionalities are also available as HTTP API 13. Real-time push notification system (with SignalR integration) 14. Chat system (with SignalR integration) 15. Background job system (with Hangfire integration) 16. Multiple time zone support for application, tenants and users 17. Built-in global event bus for server-side events (with pre-defined events for entity changes) 18. Show and download logs from UI 19. Application setup screen 20. Personalization of layout, header, menu and footer per user 21. Tested on major PAAS providers (Azure, AWS)
Based on Strong Frameworks
1. .NET Framework 4.6.x / .NET Core 2.x (cross-platform support) 2. ASP.NET Core / ASP.NET MVC & Web API 3. EntityFramework Code-First and Migrations 4. Angular, Bootstrap, AutoMapper... 5. ASP.NET Boilerplate
Based on Metronic Theme
1. Bootstrap based 2. Responsive design 3. Multiple layout options 4. Metronic UI and components
We, at Manektech, always support the way our client wants to handle their project and we have talented and experienced software developers with us for all your technical needs. With years of experience in IT industry, ManekTech provides the best solution for your IT needs, our experiences software professionals associated with us and we always thrives to provide the expert solution to all your technical needs. We invite you to visit us for all your technical need with the best possible solution.
#Outsourcing software development company#software outsourcing company#offshore custom software development
0 notes
Text
Accelerate Your Learning: Master Angular 18 and ASP.NET 8.0

In today's fast-paced tech industry, developers need to stay ahead of the curve by mastering cutting-edge technologies. One of the best ways to ensure you’re on top of your game is to focus on Angular 18 and ASP NET 8.0. Whether you're looking to enhance your career or build the next generation of web applications, these two powerful tools can help you achieve that goal.
Both Angular 18 and ASP NET 8.0 are celebrated for their ability to create responsive, scalable, and efficient web applications. As web development continues to evolve, these platforms have proven to be game-changers, making it essential for developers to get familiar with their features, advantages, and how they can be seamlessly integrated.
Why You Should Master Angular 18 and ASP NET 8.0
Angular and ASP NET have become go-to technologies for web developers for a variety of reasons. Angular 18 allows developers to create dynamic, single-page applications that perform well on any device. With a strong focus on TypeScript, dependency injection, and a component-based architecture, Angular provides the structure needed for building modern web apps.
ASP NET 8.0, on the other hand, is the latest version of Microsoft's popular web development framework. Known for its robustness, flexibility, and support for RESTful services, ASP NET 8.0 is a comprehensive tool for building web applications and APIs. With improved performance, new features like minimal APIs, and better integration with cloud-based solutions, this framework is more powerful than ever.
Key Features of Angular 18
As one of the most popular front-end frameworks, Angular 18 offers some standout features that make it a must-learn for developers:
Enhanced Component-Based Architecture: Angular 18 emphasizes reusable components, making your code cleaner and easier to maintain.
Improved Performance: Thanks to features like lazy loading and ahead-of-time (AOT) compilation, Angular 18 helps you build lightning-fast applications.
TypeScript Support: As a statically typed language, TypeScript helps catch errors early, ensuring more reliable and stable codebases.
Reactive Forms and Directives: These are essential for handling complex user inputs and making the UI more interactive and responsive.
New Router Enhancements: With improved routing capabilities, Angular 18 simplifies navigation and ensures that users have a smooth experience.
By mastering Angular 18, you'll not only build beautiful, high-performing applications, but you'll also simplify your development process. Whether you're building e-commerce websites, social media platforms, or corporate portals, Angular 18 ensures that your application runs seamlessly across devices and browsers.
Core Features of ASP NET 8.0
ASP NET 8.0 has introduced several improvements that are crucial for web developers aiming to build high-performance, scalable applications. Some of its top features include:
Minimal APIs: These allow developers to create fast and efficient APIs with minimal configuration, reducing boilerplate code.
Cross-Platform Support: With ASP NET 8.0, you can develop applications that run on Windows, Linux, and macOS, giving you flexibility when it comes to deployment.
Integrated Cloud Support: Seamlessly integrate with cloud platforms like Azure, allowing you to leverage cloud-based services, storage, and scalability.
Blazor Integration: With Blazor, you can build interactive web UIs using C# instead of JavaScript, bridging the gap between client-side and server-side development.
Improved Security Features: ASP NET 8.0 focuses on security, providing built-in protection against cross-site scripting (XSS), cross-site request forgery (CSRF), and SQL injection.
By learning ASP NET 8.0, you position yourself to build reliable, secure, and efficient web applications. Its tight integration with Microsoft Azure also makes it ideal for developers looking to deploy cloud-based applications.
How Angular 18 and ASP NET 8.0 Work Together
One of the most exciting aspects of learning Angular 18 and ASP NET 8.0 is the potential for integrating these two powerful tools. By combining Angular 18 on the front end with ASP NET 8.0 on the back end, developers can create full-stack applications that are both high-performing and scalable.
For example, Angular 18 can be used to build the client-facing portion of your application, handling everything from data binding to UI rendering. Meanwhile, ASP NET 8.0 can manage the back-end logic, database operations, and API connections. This combination gives you the best of both worlds: a responsive user interface powered by Angular 18 and a robust, secure server powered by ASP NET 8.0.
The ability to integrate these technologies is especially valuable for developers working in enterprise environments, where performance, scalability, and maintainability are key. Mastering both Angular 18 and ASP NET 8.0 enables you to build applications that can handle large-scale traffic, complex business logic, and multiple user interactions with ease.
Advantages of Learning Angular 18
If you're on the fence about whether or not to invest time in Angular 18, here are a few key reasons why it should be on your radar:
High Demand: As more companies transition to web applications, there's an increasing demand for Angular developers.
Large Community Support: With an active community of developers, finding resources, tutorials, and help for Angular 18 is easier than ever.
Flexible and Modular: Angular's component-based architecture makes it easy to break down large applications into manageable pieces, improving maintainability.
End-to-End Framework: From routing to forms, Angular 18 offers a comprehensive solution for front-end development, meaning you won't need to juggle multiple libraries or frameworks.
Mobile-First Focus: As the world moves toward mobile-first development, Angular 18 ensures that your applications are optimized for performance across all devices.
Why You Shouldn't Miss Out on ASP NET 8.0
Learning ASP NET 8.0 is an investment in your future as a developer. Here are a few compelling reasons to add this framework to your skillset:
Cross-Platform Capabilities: Develop applications that run on any operating system, expanding your deployment options.
Cloud Integration: With ASP NET 8.0, deploying applications to the cloud is straightforward and efficient, particularly with services like Azure.
Security-First Approach: Built-in security features make it easy to protect your application from common web vulnerabilities.
Highly Scalable: If you’re working on applications that need to scale—either due to traffic or data size—ASP NET 8.0 is designed to handle it without sacrificing performance.
Developer-Friendly Tools: Visual Studio, Azure DevOps, and other Microsoft tools integrate seamlessly with ASP NET 8.0, making development, testing, and deployment easier.
How to Get Started
Whether you're new to web development or an experienced programmer, diving into Angular 18 and ASP NET 8.0 is easier than you think. There are numerous online resources, tutorials, and courses designed to help you master these technologies.
For Angular, the best place to start is by exploring TypeScript and understanding the component-based architecture. Once you're comfortable with those, dive into topics like routing, forms, and directives.
For ASP NET, begin by familiarizing yourself with the basics of C# and .NET Core. From there, you can start building simple applications, gradually incorporating advanced features like minimal APIs, Blazor, and cloud integration.
Conclusion
By mastering both Angular 18 and ASP NET 8.0, you'll become a full-stack developer capable of building modern, responsive, and scalable web applications. These technologies are in high demand, and by learning them, you're setting yourself up for long-term success in the development world. Whether you're looking to accelerate your learning or future-proof your career, the combination of Angular 18 and ASP NET 8.0 will provide you with the tools you need to build powerful, cutting-edge applications.
So, what are you waiting for? It’s time to Accelerate Your Learning: Master Angular 18 and ASP NET 8.0 and take your web development skills to the next level!
0 notes
Text
What is ASP.NET boilerplate framework?
Coming with a new enterprise of a web application is a tough task. Knowing that all the applications require some tasks in common, we often end up repeating ourselves. Today we can see many companies coming with their own libraries or application frameworks to accomplish these common tasks without repeating the common tasks. However, there are still some companies which copy certain parts of prevailing applications and build stat point for a new application.
Well, the first approach mentioned here is undoubtedly good and developing if your organization is big and has sufficient time to work on such frameworks.
Ever wondered, what if you can share more and repeat less? Imagine if instead of per company or per project, the DRY principle gets universally implemented. I accept that it sounds naïve but there should be a starting point.
DO YOU KNOW ABOUT ASP.NET BOILERPLATE FRAMEWORK?
Well, for those of you who don’t know, ASP.NET boilerplate framework is considered as the beginning of new modern day web applications. The ASP.NET web application framework is aimed to be a general purpose framework and a project model.
The web application framework makes use of familiar tools and implements best measures to avail you a SOLID development experience.
To understand what it does, let us understand the server-side and client-side individually.
Client Side
It avails project templates for multi-page Applications and Single-page applications.
The javascript libraries that are used often are configured and included by default.
It also has distinct APIs for certain common tasks like showing notifications and alerts, making AJAX requests, blocking UI etc.
By using dynamic Web API layer it creates dynamics javascript proxies. The same eventually call applications services with ease.
Server Side
It is based on the new Web API and ASP.NET MVC.
Flawlessly implements Domain Driven Design and layered architecture.
It also provides you space to develop compostable & reusable modules.
It implements & supports database migrations3
WOULD YOU LIKE TO HIRE ASP.NET DEVELOPER
A CONCLUSION OF AN ASP.NET BOILERPLATE FRAMEWORK
The ASP.NET Web Application Framework comes with base interfaces, classes, and tools that give you ease in building large-scale applications. However, as it is said, nothing comes with all doom and all bloom. There’s a bit of each. Before you go with it, we just want you to know that it isn’t one of Rapid Application Development (RAD) tools which give you an infrastructure to develop applications without using codes.
Also, it isn’t a code generation tool. But yes, it comes with numerous other features that develop codes at run-time. Having said these, we just want to clarify that this impeccable framework isn’t an all-in-one offering of technology. However, the areas it serves, it is best for them. Few of the renowned tools that it uses include Castle Windsor as DI Container, Log4Net for logging, AngularJs for SPA framework and more.
Originally Published by Concetto Labs > What is ASP.NET boilerplate framework?
0 notes
Text
The open source Carter Community Project adds opinionated elegance to ASP.NET Core routing
I blogged about NancyFX 6 years ago and since then lots of ASP.NET open source frameworks that build upon - and improve! - web development on .NET have become popular.
There's more than one way to serve and angle bracket (or curly brace) my friends!
Jonathan Channon and the Carter Community (JC was a core Nancy contributor as well) have been making a thin layer of extension methods and conventions on top of ASP.NET Core to make URL routing "more elegant." Carter adds and formalizes a more opinionated framework and also adds direct support for the amazing FluentValidation.
One of the best things about ASP.NET Core is its extensibility model and Carter takes full advantage of that. Carter is ASP.NET.
You can add Carter to your existing ASP.NET Core app by just "dotnet add package carter" and adding it to your Startup.cs:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddCarter(); } public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(builder => builder.MapCarter()); } }
At this point you can make a quick "microservice" - in this case just handle an HTTP GET - in almost no code, and it's super clear to read:
public class HomeModule : CarterModule { public HomeModule() { Get("/", async (req, res) => await res.WriteAsync("Hello from Carter!")); } }
Or you can add Carter as a template so you can later "dotnet new carter." Start by adding the Carter Template with "dotnet new -i CarterTemplate" and now you can make a new boilerplate starter app anytime.
There's a lot of great sample code on the Carter Community GitHub. Head over to https://github.com/CarterCommunity/Carter/tree/master/samples and give them more Stars!
Carter can also cleanly integrate with your existing ASP.NET apps because, again, it's extensions and improvements on top of ASP.NET. Now how you can add Carter to a ASP.NET Core app that's using Controllers in the MVC pattern just like this:
public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(builder => { builder.MapDefaultControllerRoute(); builder.MapCarter(); }); }
Then easily handle a GET by returning a list of things as JSON like this:
this.Get<GetActors>("/actors", async (req, res) => { var people = actorProvider.Get(); await res.AsJson(people); });
Again, check out Carter on GitHub at and follow https://twitter.com/CarterLibs on Twitter!
Sponsor: Like C#? We do too! That’s why we've developed a fast, smart, cross-platform .NET IDE which gives you even more coding power. Clever code analysis, rich code completion, instant search and navigation, an advanced debugger... With JetBrains Rider, everything you need is at your fingertips. Code C# at the speed of thought on Linux, Mac, or Windows. Try JetBrains Rider today!
© 2019 Scott Hanselman. All rights reserved.
The open source Carter Community Project adds opinionated elegance to ASP.NET Core routing published first on http://7elementswd.tumblr.com/
0 notes
Text
The open source Carter Community Project adds opinionated elegance to ASP.NET Core routing
I blogged about NancyFX 6 years ago and since then lots of ASP.NET open source frameworks that build upon - and improve! - web development on .NET have become popular.
There's more than one way to serve and angle bracket (or curly brace) my friends!
Jonathan Channon and the Carter Community (JC was a core Nancy contributor as well) have been making a thin layer of extension methods and conventions on top of ASP.NET Core to make URL routing "more elegant." Carter adds and formalizes a more opinionated framework and also adds direct support for the amazing FluentValidation.
One of the best things about ASP.NET Core is its extensibility model and Carter takes full advantage of that. Carter is ASP.NET.
You can add Carter to your existing ASP.NET Core app by just "dotnet add package carter" and adding it to your Startup.cs:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddCarter(); } public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(builder => builder.MapCarter()); } }
At this point you can make a quick "microservice" - in this case just handle an HTTP GET - in almost no code, and it's super clear to read:
public class HomeModule : CarterModule { public HomeModule() { Get("/", async (req, res) => await res.WriteAsync("Hello from Carter!")); } }
Or you can add Carter as a template so you can later "dotnet new carter." Start by adding the Carter Template with "dotnet new -i CarterTemplate" and now you can make a new boilerplate starter app anytime.
There's a lot of great sample code on the Carter Community GitHub. Head over to https://github.com/CarterCommunity/Carter/tree/master/samples and give them more Stars!
Carter can also cleanly integrate with your existing ASP.NET apps because, again, it's extensions and improvements on top of ASP.NET. Now how you can add Carter to a ASP.NET Core app that's using Controllers in the MVC pattern just like this:
public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(builder => { builder.MapDefaultControllerRoute(); builder.MapCarter(); }); }
Then easily handle a GET by returning a list of things as JSON like this:
this.Get<GetActors>("/actors", async (req, res) => { var people = actorProvider.Get(); await res.AsJson(people); });
Again, check out Carter on GitHub at and follow https://twitter.com/CarterLibs on Twitter!
Sponsor: Like C#? We do too! That’s why we've developed a fast, smart, cross-platform .NET IDE which gives you even more coding power. Clever code analysis, rich code completion, instant search and navigation, an advanced debugger... With JetBrains Rider, everything you need is at your fingertips. Code C# at the speed of thought on Linux, Mac, or Windows. Try JetBrains Rider today!
© 2019 Scott Hanselman. All rights reserved.
The open source Carter Community Project adds opinionated elegance to ASP.NET Core routing published first on https://deskbysnafu.tumblr.com/
0 notes
Text
Create a Windows Service in ASP.NET C# - .NET Framework

In this post I'll briefly explain how to create and configure a custom Windows Service in C# using Visual Studio 2019. Before we start, it could be wise to quickly summarize what a Windows Service acqually is and how it differs from a standard console program or desktop application. NOTE: the most recent version of the source code explained in this post is now fully available on GitHub: if you like it, be sure to give it a star!
Introduction
In Windows-based operating systems, the term Windows Service refers to a computer program without a user-interface that completely operates in the background. If you know Unix-based environments, you could think of it as a Windows version of a typical Unix daemon. A Windows service must conform to the interface rules and protocols of the Service Control Manager, the kernel component responsible for managing Windows services. Once installed, the Windows Service can be configured using the Service Control Manager (services.exe) to start when the operating system is started and run in the background as long as Windows is running; alternatively, they can be started manually or by an event. It's also possible to manually pause, stop and restart the service. Each service can also be configured to run within a context of a specific user or system account: for example, most Windows services that come shipped with the OS are pre-configured to run within the context of three system accounts: System, Network Service and Local Service. Such behaviours allow them to operate even when the machine is unmanaged and/or a standard user is not logged on. To get a glimpse of all services running on a Windows machine you can either: Open Control Panel, then navigate to the Administrative Tools and click on the Services icon. Press Window + R to open the Run window, then type services.msc and press ENTER.
Create the Windows Service Project
Open Visual Studio 2019 and select Create a new project from the initial dashboard. Type Windows Service into the filter textbox near the top to quickly find out the project template we're looking for: select the Windows Service (.NET Framework) project template and click Next.

Give the project a name and create it. After a few seconds, you should be prompted with your newly-created project and a blank page showing the Service1.cs file in Design Mode.
Create an Installer
The next thing we have to do is to create an Installer, which is the component that will register our Service with the Service Control Manager. To do that, right-click on the blank area in the Design View of the Service1.cs file and select Add Installer from the contextual menu, as shown in the screenshot below:

Once you do that, a new ProjectInstaller.cs file will be added to the project. Save everything (CTRL + SHIFT + S), then open the ProjectInstaller.Designer.cs file and take a look at the InitializeComponent() method, which defines some important settings of our service: its name and display name, the account context used to run it, and so on.
Configure the Installer
Locate the lines defining the Username and Password (both set to null by default) and add the following line right above them to make our service use the LocalSystem account context: this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; Right after that, locate the line of code defining the ServiceName and change it accordingly: this.serviceInstaller1.ServiceName = "WindowsService.NET"; You can also specify a Display Name and a Description by adding the relevant source code lines, in the following way: this.serviceInstaller1.DisplayName = "WindowsService.NET"; this.serviceInstaller1.Description = "A sample Windows Service boilerplate written in C# using NET Framework and VS2019"; Here's how your InitializeComponent() method should look like after the changes: private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // // serviceInstaller1 // this.serviceInstaller1.ServiceName = "WindowsService.NET"; this.serviceInstaller1.DisplayName = "WindowsService.NET"; this.serviceInstaller1.Description = "A sample Windows Service boilerplate written in C# using NET Framework and VS2019"; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer { this.serviceProcessInstaller1, this.serviceInstaller1}); } That's it for the installer: now let's switch to the Windows Service code itself.
Create a sample recurring task
Open the Service1.cs file and switch to Code View. As we can see, there are three main methods here: the Service1() method, aka the constructor, which internally calls the InitializeComponents() method that we modified in the previous paragraph. The OnStart() method, which is called once when the service is started. The OnStop() method, which will be called once when the service is stopped. For our sample boilerplate we'll just add a basic timelapse logging feature to the default code: public partial class Service1 : ServiceBase { Timer Timer = new Timer(); int Interval = 10000; // 10000 ms = 10 second public Service1() { InitializeComponent(); this.ServiceName = "WindowsService.NET"; } protected override void OnStart(string args) { WriteLog("Service has been started"); Timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); Timer.Interval = Interval; Timer.Enabled = true; } private void OnElapsedTime(object source, ElapsedEventArgs e) { WriteLog("{0} ms elapsed."); } protected override void OnStop() { Timer.Stop(); WriteLog("Service has been stopped."); } private void WriteLog(string logMessage, bool addTimeStamp = true) { var path = AppDomain.CurrentDomain.BaseDirectory; if (!Directory.Exists(path)) Directory.CreateDirectory(path); var filePath = String.Format("{0}\\{1}_{2}.txt", path, ServiceName, DateTime.Now.ToString("yyyyMMdd", CultureInfo.CurrentCulture) ); if (addTimeStamp) logMessage = String.Format(" - {1}", DateTime.Now.ToString("HH:mm:ss", CultureInfo.CurrentCulture), logMessage); File.AppendAllText(filePath, logMessage); } } As we can see, we added the following stuff: The Timer private variable, which host a standard timer (from System.Timers namespace). The Interval private variable, which globally defines the timer interval in milliseconds. The OnElapsedTime() private method, which will be called upon each timer interval cycle. The WriteLog() private method, which logs a custom log message to a daily log file persisted on disk: such file will be created within the folder that hosts the service executable. A minimal implementation in the existing OnStart() and OnStop() methods to put everything together. While we were there, we also changed the service's default name from Service1 to WindowsService.NET by adding the following line in the constructor, rightbelow the InitializeComponent() call: this.ServiceName = "WindowsService.NET"; Alternatively, the ServiceName property can also be changed from within the Service1.Designer.cs file's InitializeComponent() method. That's basically it: our service is ready to be installed and tested!
Installing the Service
To install our service, build the project in Release mode: once done, copy the WindowsService.NET.exe file from /bin/Release/ to a more "handy" folder - such as C:\Temp\WindowsInstaller\. Right after that, open a Command Prompt with administrative rights and type the following: "C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" "C:\Temp\WindowsService.NET\WindowsService.NET.exe" You should receive a quick confirmation message saying that everything went good. Alternative install using SC CREATE If you don't want to use installutil.exe, you can also install your service using the sc create command with the following syntax: sc create "WindowsService.NET" binPath="C:\Temp\WindowsService.NET\WindowsService.NET.exe" However, if you do that, you'll have to manually specify the service name: also, the service Description won't be shown in the service list UI window (see below).
Testing the Service
Use Control Panel > Administrative Tools > Services to open the service list and scroll down until you'll find our new service:

That's our boy! From here we can either manually start it or set it to automatic, so that it will be started whenever the system starts. However, I strongly suggest to not do that for now, since it would permanently drain your system resources if you forget to disable it - it's just a sample service after all! Let's just start it and take a look at the log file, which should be found in the executable folder: C:\Temp\WindowsService.NET\ If everything went good, the log should be similar to this screenshot:

Removing the Service
To remove our service, open a Command Prompt with administrative rights and type the following command: sc delete "WindowsService.NET";
Troubleshooting
It's worth noting that, whenever the service encounters an unhandled exceptions while operating, it will crash without writing anything to the Windows event log. For that very reason, I strongly suggest to wrap your main execution methods within a try/catch block and log any possible exceptions on disk - or somewhere else - so you can better understand what's going on. Such task can be very easy using the WriteLog() function within our sample code: don't forget to do that!
Conclusion
That's it: I hope that this guide will help other ASP.NET C# developers to create awesome Windows Services to fullfill their needs! Read the full article
0 notes
Text
React Native, Push Notifications and Firebase - Part 1 of 5
In this five-part tutorial we'll see how we can create a sample React Native app (you might call it a "Hello World" or "boilerplate") that will be capable of receiving Push Notifications using Firebase: this can be a great headstart for React Native beginners, yet also for those intermediate or experienced developers who want to know more about push notifications: how they work, what are their best usage scenarios and how much they can be an improvement for almost any mobile app. For the sake of simplicity, the tutorial has been splitted into multiple parts, each one dedicated to a specific sub-topic: Part 1 of 5: Understanding Push Notifications, in which we'll try to understand how push notifications actually are and the impact they could have on a typical client-server app. Part 2 of 5: Setup React Native and Firebase, where we'll deal with the installation and configuration of our whole development stack: React Native, the Firebase SDK and the Visual Studio Code environment, together with the required settings to get our app ready to work with Android and iOS. Part 3 of 5: Configure the Firebase Service, in which we'll setup the Firebase Service to ensure that our React Native app will be able to receive push notifications through the Firebase API on any Android and iOS device. Part 4 of 5: Design and Test the React Native UI, where we'll test our front-end skills by laying out a React-Native UI in order to make our app actually able to receive push notifications and send HTTP requests to the server to remotely keep track of our actions - and possibly fire subsequent push notifications to other clients. Part 5 of 5: Server-Side Handler, in which we'll use ASP.NET Core to create a sample, lightweight web server that will be able to receive HTTP requests issued by the clients and/or feed them with push notifications through the Firebase API. In this first post we'll talk about push notifications.
Introduction
Before going further, let's spend a couple minutes to properly understand how a push notifications workflow tipically works for most apps, which can be useful to understand what do we have to do. Let's say we want to create a Personal Calendar app that can be used to configure events and (optionally) schedule reminders that will be sent to the user whenever these events are about to start: the best method we can use to "send" these reminders are notifications. The user will see them, even if the app is minimized, and (optionally) click on them to open the app and get further info on that topic. This is a typical example of an interactive app that makes use of notifications to fullfill some of its features: the users add events, configure reminders and receive notifications accordingly. The big question here is, who is in charge of sending these notifications? The answer of such question is not trivial, as it entirely depends on how the app itself actually works. Serverless or Client-Server? Here's a list of the most common implementation patterns that we could theoretically follow to implement a Personal Calendar app in a decent way: Serverless: both the app and the events database, including the reminders, are entirely installed on the mobile phone. We won't need to fetch/receive anything from the web, therefore we won't need a server - as well as dealing with the whole HTTP stack. Such approach grants a tremendous gain in terms of development costs and overall complexity, which definitely is a a huge pro, yet also a lot of cons in terms of data resilience, backup plans, app usage through different clients and/or devices, and a lot of "cloud-based" features we would be forced to give up. These cons are often very relevant, to the point that serverless apps are a small minority. It's a viable approach for simple apps that are supposed to do specific "offline" tasks, such as torch lightning or size measurement apps. Server-Client: the app is meant to be a client installed on the mobile phone, but the database, as long as most business logic and data-handling tasks, are handled using a collection of services installed on a remote public or private server. This is the most common approach for almost any app nowadays: games, instant-messaging, social networks, and almost any app which requires to fetch any possible kind of data from the outside. Push Notifications If we choose to make our Personal Calendar a serverless app, we wouldn't need to handle push notifications at all... because there would be nothing to push. The word "push" implies that there's something coming from the outside: serverless apps doesn't interact with a server, therefore there would be noting to receive. Conversely, if we choose to follow the client-server path, our Personal Calendar app could greatly benefit from such feature: push notifications are the perfect way to have the server take track of our reminders and sends them to any client that should receive them: that way we could support multiple clients for a single user, a "reminder sharing" feature that would allow us to "share" our events (and their reminders) with other users, and so on. Long story short, we can say that push notifications would be a huge feature even for a rather "simple" app such as a Personal Calendar, meaning that we should really favor the client-server approach over the serverless one. In more general terms, we can say that whenever there are good reasons to pick the client-server approach, it means that our app could also benefit from push notifications. That being the case, imagine how important push notifications would be for instant-messaging apps like Whatsapp, Line, Telegram, and virtually any app who needs to support some form of real-time communication between clients. In these kinds of scenarios push notifications could play a major role, as they can be used to istantly notify any relevant action performed by a single client to any other "connected" clients. Push Notifications Workflow The following diagram depicts a standard Push Notification Workflow that could be used on a typical instant messaging app:
As we can see, the push notifications are originated by a single HTTP request sent by the Client to the Server (black line) to inform it about a relevant action: a message, yet also a channel join (or part), an avatar change, a logout, and so on. The HTTP request is received by the server in a RESTful fashion and initiates a series of subsequent tasks: The Server, typically a Web Server, calls the Database Server (orange line) to log the action performed by the client and save the relevant changes (for example, save its new message in the messages table). However, the interaction with the DB Server is bidirectional, as the server, immediately after writing the new data, also needs to retrieve from the DB the necessary info required to send a push notification to the affected clients to notify them of the new action - in our example, the new received message. Those info are typically the unique IDs which the notification service can use to identify those client: if we use Firebase, they are called FCM Tokens (read here for additional info). It goes without saying that those IDs, which act just like a fingerprint of each client, must be collected before sending the push notifications, for example when the client installs the app for the first time, or the user creates its account, or during the login phase... But we'll deal with that later on. Once the action has been logged and/or saved and the unique tokens have been retrieved, the Server can call the notification service (in our example, Google Firebase) using its API (blue line), and tell it to send the push notifications to the affected clients: doing that is almost as easy as sending the new action's details (in our example, the new message) to the notification service, together with the list of unique tokens to send them to. The notification service (in our example, Firebase) sends the push notifications to the clients (green lines), who can receive and consume them thanks to the notification service's SDK (the client-side modules) which has been installed on them during the development phase. A push notification can be consumed in a number of ways: showing its title and body attribute values in the device's notifications area, showing a dedicated popup, launch our app and/or bring it to foreground, and so on. In our example, since the push notification contains info about a new message, consuming it would most likely mean to show it in the chat view within a "bubble", create a notification popup to tell the user that a new message has arrived, and maybe even incrementing the "notification counter" on our app's icon (if the app is minimized). That's basically it: now we should have a pretty clear idea about what we need to implement whenever we want to add push notification support to our app. Part 2 of 5: Setup React Native and Firebase Read the full article
0 notes